var util   = require('../../../utils/util.js')
var WxParse = require('../../../utils/wxParse/wxParse.js')
import cache from '../../../utils/cache.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    windowHeight: wx.getSystemInfoSync().windowHeight + 50,
    pageHeight: wx.getSystemInfoSync().windowHeight + 10000,
    style: "max-height: 200rpx;",
    showText: "显示全部",
    tabActive: 0,
    desc: "",
    serviceList: [],
    serviceIndex: -1,
    currentIntro: null, //点击的服务介绍
    pageNum: 0,
    commentList: [], //评价列表
    total: 100,
    starRating: 1,
    openId: 1,
    className: '',
    department_id: ''
  },
  caculateScrollPageHeight () { // 计算动态高度
    var me = this
    if (me.caculated) return
    console.log('可用高度',wx.getSystemInfoSync().windowHeight)
    wx.createSelectorQuery().selectAll('.comment-container').boundingClientRect(function(rects){
      rects.forEach(function(rect){
        console.log('rect', rect.bottom)
        me.setData({
          pageHeight: rect.bottom
        })
        me.caculated = true
        rect.id      // 节点的ID
        rect.dataset // 节点的dataset
        rect.left    // 节点的左边界坐标
        rect.right   // 节点的右边界坐标
        rect.top     // 节点的上边界坐标
        rect.bottom  // 节点的下边界坐标
        rect.width   // 节点的宽度
        rect.height  // 节点的高度
      })
    }).exec()
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('路由穿过来的参数',this.options)
    this.getServiceList();
    this.getDec();
    this.setData({
      className: options.name
    })
  },
  formatString: function (str) { // 正则过滤样式
    var reg = /<style>[\s\S]*?<\/style>/ig;
    return str.replace(reg, '')
  },
  /**
   *  获取服务介绍
   */
  getDec(){
    let params = { id: this.options.id };
    var self = this;
    wx.request({
      url: wx.envConfig.host + '/department/get?params=' + JSON.stringify(params),
      method: 'get',
      success: function (res) {
        WxParse.wxParse('article', 'html', self.formatString(res.data.datas.briefing), self, 5)
      }
    })
  },
  /**
   * 获取服务列表
   */
  getServiceList(){

    let params = { id: this.options.id };
    var self  = this;
    wx.showLoading({title: '正在加载...'})
    wx.request({
      url: wx.envConfig.host + "/service/queryServiceByDeaprtment?params=" + JSON.stringify(params),
      method: 'get',
      success: function (res) {
        console.log('res111', res)
        wx.hideLoading()
        if (res.data.datas.length > 0) {
            var serviceList = res.data.datas.map(it => {
                return {
                    id: it.id,
                    name: it.name,
                    service_time: it.service_time,
                    service_price: it.service_price,
                    dynamic_money: it.dynamic_money,
                    department_id: it.department_id,
                    type: it.type,
                    serviceDescribeList: it.serviceDescribeList,
                    freeService: it.freeService
                }
            })
            self.setData({
                department_id: serviceList[0].department_id,
                serviceList: serviceList
            })
            self.setData({
              pageHeight: wx.getSystemInfoSync().windowHeight
            });
        } else {
          wx.showToast({
            title: '此科室暂无服务'
          });
          return
        }
        self.loadMore()
      }
    })
  },
  formatPrice(money) { // 价格格式化
    money = money.toString();
    var reg = /(?=(\B)(\d{3})+$)/g;
    return money.replace(reg, ',')
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    console.log('下拉')
    this.refreshEvalute()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log('12356')
    if (this.data.tabActive == 2) {
      // this.loadMore();
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },


  // 刷新评价
  refreshEvalute () {
    console.log('refreshEvalute')
    this.setData({
      pageNum: 0
    })
    this.loadMore()
  },
  /**
   * 加载更多评价
   */
  loadMore: function () {
    console.log('loadMore')
    var self = this;

    if (this.data.commentList.length >= this.data.total) {
      console.log("到底了")
      return;
    }
    console.log('this.data.department_id',this.data.department_id);
    var params = {
      "p": ++this.data.pageNum,
      "pageSize": 6,
      "nPages": "5",
      "types": '1,2', // 满意度
      "department_id": this.data.department_id,//this.id,
    }
    var url = wx.envConfig.host + '/evaluate/pageByOrderEvaluate' + "?params=" + JSON.stringify(params);
    wx.request({
      url: url,
      method: 'POST',
      success: function (result) {
        console.log('request comment:', result)
        var total = result.data.datas.total;
        result.data.datas.list.forEach(it => {
          it.type == 1 ? it.levelArr = [1,2,3,4,5] :
            it.type == 2 ? it.levelArr = [1,2,3,4] :
             it.type == 3 ? it.levelArr = [1,2,3] :
              it.type == 4 ? it.levelArr = [1,2] :
               it.type == 5 ? it.levelArr = [1] :
                it.levelArr = []
          it.updateTime = util.parseTime(it.update_time, '{y}.{m}.{d}')
        })
        var tempCommentList = self.data.commentList.concat(result.data.datas.list);
        self.setData({
          total: total,
          commentList: tempCommentList
        })
        self.caculateScrollPageHeight();
        wx.stopPullDownRefresh();
      },
      fail: function ({ errMsg }) {
        console.log('request fail', errMsg);
        wx.stopPullDownRefresh();
      }
    })
  },

  /**
   * 点击科室详情按钮
   */
  showContent: function () {
    console.log(this.data)

    if (this.data.showText == '显示全部') {
      this.setData({
        style: "",
        showText: "收起局部"
      })
    } else {
      this.setData({
        style: "max-height: 200rpx;",
        showText: "显示全部"
      })
    }
  },

  /**
   * 点击可选购服务
   */
  selectService: function () {
    this.setData({
      tabActive: 0
    })
  },

  /**
   * 点击介绍
   */
  selectDesc: function () {
    this.setData({
      tabActive: 1
    })
  },

  /**
   * 点击科室评价
   */
  selectEvalute: function () {
    this.setData({
      tabActive: 2
    })
  },

  /**
   * 点击服务列表选择按钮
   */
  selectSeivice: function (event) {
    var index = event.currentTarget.dataset.index;

    var tempIndex = -1;
    if (index !== this.data.serviceIndex) {
      tempIndex = index;
    }
    this.setData({
      serviceIndex: tempIndex
    })
  },

  /**
   * 点击购买服务
   */

  buy: function (event) {
    console.log('服务id', event.currentTarget.dataset.service.id)
    console.log('服务id`````get', getApp().globalData.userInfo.id)
    var service = event.currentTarget.dataset.service;
    var url = ''
    var _this = this;
    getApp().getAppUserInfo(true).then((res) => {
      var cooki;
      var userInfo;
      if (!res) {  //获取用户信息失败请重新登录
        wx.showModal({
          title: '提示',
          content: '获取用户信息失败请重新登录',
          success: function (res) {
            if (res.confirm) {
              wx.navigateTo({
                url: '../../login/login'   //跳转登录界面
              })
            }
          }
        })
        return
      }
      cooki = wx.getStorageSync('cookiez');
      console.log('cooki', cooki);
      userInfo = res
      if (userInfo.verify !== 1) {  //用户未认证
        wx.showModal({
          title: '提示',
          content: '用户未认证',
          success: function (res) {
            if (res.confirm) {
              wx.navigateTo({
                url: '../../mine/personalInformation/personalInformation'  //跳转认证界面
              })
            }
          }
        })
        return
      }
      if (cooki) {
        let params = {
          'service_id': event.currentTarget.dataset.service.id,
          'user_doctor_id': userInfo.id
        }
        var URL = wx.envConfig.host + '/order/findByServiceId?params=' + JSON.stringify(params)
        wx.request({
          url: URL,
          method: 'GET',
          success: function (res) {
            console.log('res`````orderid', res)
            var orders = res.data.datas;
            if (orders.length == 0) {
              _this.createOrder(userInfo, service, cooki)
            } else if (orders.length ==1) {
              wx.showModal({
                title: '提示',
                content: '您有订单未填写订单信息，是否先去完善信息？',
                cancelText: '仍要下单',
                confirmText: '完善订单',
                cancelColor: '#4825BF',
                confirmColor: '#4825BF',
                success: function (res) {
                  if (res.confirm) {
                    wx.navigateTo({
                    url: '../../order/orderDetail/orderDetail?id=' + res.data.datas[0].order_id
                  })
                  } else {
                    _this.createOrder(userInfo, service, cooki)
                  }
                }
              })
            } else{
              wx.showModal({
                title: '提示',
                confirmText: '完善信息',
                cancelText: '否',
                cancelColor: '#4825BF',
                confirmColor: '#4825BF',
                content: '您尚有2个待完善信息的订单,请先完善信息再提交新的订单',
                success: function (res) {
                  if (res.confirm) {
                    wx.navigateTo({
                      url: '../../order/orderList/orderList?index=1'
                    })
                  }
                }
              })
            }
          },
          fail: function (res) { },
          complete: function (res) { },
        })
      } else {
        wx.showModal({
          title: '提示',
          content: '您还未注册,立即注册',
          confirmText: '好的',
          success: function(res) {
            if (res.confirm) {
              url = '../../mine/regist/regist'
              wx.navigateTo({
                url: url
              })
            }
          }
        })
      }
    })
  },
  createOrder: function (userinfo,serviceItem, cooki) {//创建订单
    console.log('cooki', cooki);
    let self = this;
    let retuslt = {
      order: { fileds: {} }
    };
    retuslt.order.user_doctor_id = userinfo.id;
    retuslt.order.service_id = serviceItem.id;
    //订单价格
    retuslt.order.pay_money = JSON.parse(serviceItem.service_price).service_price || 0;
    //订单类型
    retuslt.order.type = serviceItem.type;
    //status为 0 时的页面状态(0信息保存，1验证码状态)
    retuslt.order.page_status = 0;
    wx.request({ 
      url: wx.envConfig.host + "/order/createOrder?" + "cookiez=" + cooki,
      method:"POST",
      data: retuslt,
      success:function(res){
        console.log("res", res)
        wx.navigateTo({
          url: './uploadCTdata/uploadCTdata?id='+res.data.datas.order_id
        })
      /**
       * 创建订单完成，去上传页面
       */
      }
    })
  },
  /**
   * 查看服务介绍
   */
  linkToDescription: function (event) {
    var intro = event.currentTarget.dataset.intro;
    if (intro.briefing) {
      intro.briefing = this.formatString(intro.briefing);
    }
    cache.set('current_selected_service_son', intro)
    // this.setData({
    //   currentIntro: intro
    // })
    wx.navigateTo({
      // url: './serviceContent/serviceContent?intro=' + JSON.stringify(intro),
      url: './serviceContent/serviceContent'
    })
  },

  /**
   * 关闭服务介绍
   */
  hideIntro: function (event) {
    this.setData({
      currentIntro: null
    })
  }
})